import UIKit
import MobileCoreServices
import UniformTypeIdentifiers
/**
 系统文件读取
 */
public class CHFileDataLoader: NSObject {
    
    // MARK: - 类型定义
    public struct FileInfo {
        public  let fileURL: URL
        public  let fileName: String
        public  let fileSize: Int64
        public  let data: Data?
        public   let error: Error?
    }
    
    public  typealias CompletionHandler = ([FileInfo]) -> Void
    
    // MARK: - 属性
    private var completion: CompletionHandler?
    private weak var presentingViewController: UIViewController?
    private var currentFolderURL: URL?
    private var selectionMode: SelectionMode = .files
    
    enum SelectionMode {
        case folder
        case files
    }
    
    // MARK: - 文件选择方法
    public func loadFilesFromFilePicker(
        presenting viewController: UIViewController,
        allowMultiple: Bool = true,
        completion: @escaping CompletionHandler
    ) {
        self.selectionMode = .files
        self.presentingViewController = viewController
        self.completion = completion
        
        if #available(iOS 14.0, *) {
            // iOS 14+ 推荐方式
            let pdfType = UTType.pdf
            let documentPicker = UIDocumentPickerViewController(
                forOpeningContentTypes: [pdfType],
                asCopy: false
            )
            
            documentPicker.delegate = self
            
            // 多选设置技巧 :cite[2]
            if allowMultiple {
                if #available(iOS 11.0, *) {
                    documentPicker.allowsMultipleSelection = true
                }
            }
            
            viewController.present(documentPicker, animated: true) {
                // 某些情况下需要在呈现后再次设置 :cite[2]
                if #available(iOS 11.0, *), allowMultiple {
                    documentPicker.allowsMultipleSelection = true
                }
            }
            
        } else {
            // iOS 14 之前的回退方案
            let documentPicker = UIDocumentPickerViewController(
                documentTypes: [kUTTypePDF as String],
                in: .open
            )
            documentPicker.delegate = self
            
            if #available(iOS 11.0, *), allowMultiple {
                documentPicker.allowsMultipleSelection = true
            }
            
            viewController.present(documentPicker, animated: true, completion: nil)
        }
    }
    
    // MARK: - 处理选中的文件
    private func processSelectedFiles(_ fileURLs: [URL]) {
        var fileInfos: [FileInfo] = []
        
        for fileURL in fileURLs {
            guard fileURL.startAccessingSecurityScopedResource() else {
                let errorInfo = FileInfo(
                    fileURL: fileURL,
                    fileName: fileURL.lastPathComponent,
                    fileSize: 0,
                    data: nil,
                    error: NSError(domain: "FileDataLoader", code: 1, userInfo: [
                        NSLocalizedDescriptionKey: "无法访问选定的文件"
                    ])
                )
                fileInfos.append(errorInfo)
                continue
            }
            
            let fileInfo = readFileData(fileURL)
            fileInfos.append(fileInfo)
            
            fileURL.stopAccessingSecurityScopedResource()
        }
        
        completion?(fileInfos)
    }
    
    // MARK: - 读取文件数据
    private func readFileData(_ fileURL: URL) -> FileInfo {
        do {
            let resources = try fileURL.resourceValues(forKeys: [.fileSizeKey, .nameKey])
            let fileSize = Int64(resources.fileSize ?? 0)
            let fileName = resources.name ?? fileURL.lastPathComponent
            
            if fileSize > 100 * 1024 * 1024 {
                throw NSError(domain: "FileDataLoader", code: 2, userInfo: [
                    NSLocalizedDescriptionKey: "文件过大，无法读取"
                ])
            }
            
            let data = try Data(contentsOf: fileURL, options: .mappedIfSafe)
            
            return FileInfo(
                fileURL: fileURL,
                fileName: fileName,
                fileSize: fileSize,
                data: data,
                error: nil
            )
        } catch {
            return FileInfo(
                fileURL: fileURL,
                fileName: fileURL.lastPathComponent,
                fileSize: 0,
                data: nil,
                error: error
            )
        }
    }
    
    func releaseSecurityAccess() {
        if let folderURL = currentFolderURL {
            folderURL.stopAccessingSecurityScopedResource()
            currentFolderURL = nil
        }
    }
}

// MARK: - UIDocumentPickerDelegate
extension CHFileDataLoader: UIDocumentPickerDelegate {
    
    public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard !urls.isEmpty else {
            completion?([])
            return
        }
        
        switch selectionMode {
        case .folder:
            guard let folderURL = urls.first else { return }
            processSelectedFolder(folderURL)
        case .files:
            processSelectedFiles(urls)
        }
        
        presentingViewController?.dismiss(animated: true, completion: nil)
    }
    
    // 单文件选择的旧方法 - 保持兼容性
    public  func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        processSelectedFiles([url])
        presentingViewController?.dismiss(animated: true, completion: nil)
    }
    
    public func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        presentingViewController?.dismiss(animated: true, completion: nil)
    }
    
    private func processSelectedFolder(_ folderURL: URL) {
        // 您的文件夹处理逻辑
    }
}
